<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\User;

use Think\Exception;
use Think\Log;

class Train extends \Service\Common\BaseModel
{
    protected $name = 'eyes_train';


    //列表
    public function trainList($uid, $page_num, $page_size)
    {
        $where = [
            'userid' => $uid,
        ];
        $list = (array)$this->where($where)->order('id desc')->page($page_num, $page_size)->select();
        $count = $this->where($where)->count();
        return [
            $this->format($list),
            $page_count = $count,
            $page_total = ceil($count / $page_size),
        ];
    }


    public function trainSubmit($uid, $param){
        $train = M('eyes_train')->where(['id' => $param['trainid']])->find();
        if(!isset($train['id'])) throw new Exception('训练科目不存在');
        $add = [
            'trainid' => $param['trainid'],
            'userid' => $uid,
            'startime' => date('Y-m-d H:i:s'),
            'stardate' => date('Ymd'),
        ];
        $flag = M('eyes_train_log')->add($add);
        if($flag){
            return $flag;
        }else{
            throw new Exception('提交失败');
        }
    }

    public function trainUpdate($uid, $param){
        $train = M('eyes_train_log')->where(['id' => $param['id']])->find();
        if(!isset($train['id'])) throw new Exception('训练记录不存在');
        if(!$train['endtime']) throw new Exception('训练记录已更新');
        $time = time();
        $starttime = strtotime($train['startime']);
        $playtime = $time-$starttime;
        if($playtime<0) throw new Exception('更新失败');
        $flag = M('eyes_train_log')->where(['id' => $param['id']])
            ->save([
                'endtime' => date('Y-m-d H:i:s', $time),
                'playtime' => $playtime
            ]);
        if(!$flag)  throw new Exception('更新失败-1');
        $flag1 = M('eyes_task_log')->where(['taskid' => 2, 'userid' => $uid, 'record_date' => date('Y-m-d')])->find();
        if(!$flag1) OE('user')->addEyesMoney($uid, 2);
        return true;
    }


    //格式化
    public function format($list)
    {
        if (!$list) {
            return $list;
        }

        $is_one = count($list) == count($list, 1);
        $list = $is_one ? [$list] : $list;

       /* foreach ($list as &$row) {
            $row['relation_label'] = $this->relate[$row['relation']];
        }*/
        return $is_one ? $list[0] : $list;
    }



}